import {
  PutRes,
  Media,
  PageData,
  DisableRes,
  getMediaDto,
  putMediaDto,
  MediaGateway,
  getWriteSignDto,
  getReadURLDto,
  disableMediaDto,
  MediaInterfaceWithDerive,
  getOcrFaPiaoDto,
} from "qqlx-core";

import { ViewBase, ViewBaseAction } from "../view-base";
import { MediaSchema } from "@/pond/schema-media";

export class ViewMedia extends ViewBase<Media> implements ViewBaseAction<Media>, MediaInterfaceWithDerive<{}> {
  private static instance: ViewMedia;
  static getInstance(options?: { isSingleton?: boolean }) {
    if (options?.isSingleton === false) {
      return new ViewMedia();
    }

    if (!this.instance) this.instance = new ViewMedia();
    return this.instance;
  }

  private constructor() {
    super();
    this.initial();
    this.insertDefaultCondition();
  }

  getSchema(): Media {
    return new MediaSchema();
  }

  async get(input: Pick<getMediaDto, "groupId">) {
    this.pending();
    const dto = { ...input, page: this.data.entityListPage, conditionList: this.data.conditionList };
    const { list, total } = await this.$request.getByPut<getMediaDto, PageData<Media>>(MediaGateway.path, dto);

    this.data.entityListTotal = total;
    return { list, total };
  }

  async put() {
    this.pending();
    const dto = { schema: this.data.schema };
    return this.$request.put<putMediaDto, PutRes<Media>>(MediaGateway.path, dto);
  }

  async disable(dto: disableMediaDto) {
    this.pending();
    return this.$request.delete<disableMediaDto, DisableRes>(MediaGateway.path, dto);
  }

  /** 获取直传链接 */
  async getWriteSign(dto: getWriteSignDto) {
    this.pending();
    const path = `${MediaGateway.path}/sign`;
    return this.$request.getByPut<getWriteSignDto, { URL: string; media: Media }>(path, dto);
  }

  /** 获取预览链接 */
  async getReadURL(dto: getReadURLDto) {
    this.pending();
    const path = `${MediaGateway.path}/url`;
    return this.$request.getByPut<getReadURLDto, { URL: string }>(path, dto);
  }

  async getOcrFaPiao(dto: getOcrFaPiaoDto) {
    this.pending();
    const path = `${MediaGateway.path}/ocr/fapiao`;
    return this.$request.patch<getOcrFaPiaoDto, { mediaId: Media["id"]; textList: { Name: string; Value: string }[] }[]>(path, dto);
  }
}
